<template>
  <wd-form-item
    v-if="typeof props.component.display == 'undefined' || props.component.display === true"
    :component="props.component"
    :custom-field="props.customField"
  >
    <slot :name="`form-${props.component.dataIndex}`" v-bind="props.component">
      <el-radio-group v-model="value" :size="props.component.size">
        <template v-for="(item, index) in dictList[dictIndex] ?? []" :key="index">
          <el-radio :value="item.value" :disabled="item.disabled">
            {{ item.label }}
          </el-radio>
        </template>
      </el-radio-group>
    </slot>
  </wd-form-item>
</template>

<script setup>
import { ref, inject, watch } from "vue";
import { get, set, isUndefined } from 'lodash'
const props = defineProps({
  component: { type: Object, required: true },
  customField: { type: String, default: undefined },
});

const formModel = inject("formModel");
const dictList = inject("dictList");

const index = props.customField ?? props.component.dataIndex;
const dictIndex = index.match(/^(\w+\.)\d+\./)
  ? index.match(/^(\w+\.)\d+\./)[1] + props.component.dataIndex
  : props.component.dataIndex;
const value = ref(get(formModel.value, index, ""));

watch(
  () => get(formModel.value, index),
  (vl) => (value.value = vl)
);

watch( () => value.value, v => {
  set(formModel.value, index, v)
  index.indexOf('.') > -1 && delete formModel.value[index]
} )

if (value.value === "") {
  value.value = undefined;
} else if (
  !isUndefined(value.value) &&
  props.component.dict &&
  (props.component.dict.name || props.component.dict.data)
) {
  value.value = String(value.value);
}
</script>